<template>
  <el-button plain @click="add(null)" type="primary" style="margin-bottom:15px;">
    新增
  </el-button>
  <el-icon>
    <Refresh />
  </el-icon>
  <el-table :data="source" border style="width: 100%;height:674px;">
    <el-table-column type="selection" width="55" />
    <el-table-column type="index" width="55" label="序号" />
    <el-table-column prop="productName" label="商品名称" />
    <el-table-column prop="sourceproduction" label="生产批次" />
    <el-table-column prop="sourceexpirationTime" label="保质期（天）" />
    <el-table-column prop="sourcelicence" label="生产许可证号" />
    <el-table-column prop="sourceCreamFirm" label="生产企业" />
    <el-table-column prop="completeness" label="信息完善度" />
    <el-table-column prop="sourceCreamPerson" label="创建人" />
    <el-table-column prop="sourceCreamTime" label="创建时间">
      <template v-slot="scope">
        {{ scope.row.sourceCreamTime.substr(0, 19).replace("T", " ") }}
      </template>
    </el-table-column>
    <el-table-column prop="sourceUpdatePerson" label="修改人" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-link type="primary" @click="particulars(scope.row)">详情</el-link>&nbsp;&nbsp;
        <el-link type="primary" @click="del(scope.row.sourceInfoId)">删除</el-link>&nbsp;&nbsp;
        <el-link type="primary" @click="add(scope.row)">修改</el-link>
      </template>
    </el-table-column>
  </el-table>
  <div class="demo-pagination-block" style="margin-top: 10px;">
    <el-pagination v-model:current-page="pagelist.pageIdex" v-model:page-size="pagelist.pageSize"
      :page-sizes="[10, 15, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="pagelist.recordCount" />
  </div>
  <el-dialog v-model="logic.dialogFormVisible" :title="logic.istext" width="500">
    <el-form label-width="120px" label-position="right"> <!-- 统一设置 label 宽度和对齐方式 -->
      <el-form-item label="商品名称：" prop="productNameId">
        <el-select placeholder="请选择" v-model="sourceadd.productNameId" style="width: 100%;">
          <el-option v-for="item in getproduct" :key="item.productNameId" :label="item.productName"
            :value="item.productNameId" />
        </el-select>
      </el-form-item>
      <el-form-item label="生产批次：" prop="sourceproduction">
        <el-input v-model="sourceadd.sourceproduction" />
      </el-form-item>
      <el-form-item label="保质期（天）：" prop="sourceexpirationTime">
        <el-input v-model="sourceadd.sourceexpirationTime" />
      </el-form-item>
      <el-form-item label="生产许可证号：" prop="sourcelicence">
        <el-input v-model="sourceadd.sourcelicence" />
      </el-form-item>
      <el-form-item label="生产企业：" prop="sourceCreamFirm">
        <el-input v-model="sourceadd.sourceCreamFirm" />
      </el-form-item>
      <el-form-item label="封面图：" prop="SourCecoverPicture">
        <el-upload class="avatar-uploader" action="http://localhost:5175/api/Managerment/UploadImages"
          :show-file-list="false" :on-success="handleAvatarSuccess">
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="logic.dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="addSource">提交</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup lang='ts'>
import { reactive, ref, onMounted, watch } from 'vue';
import axios from 'axios'
import { useCounterStore } from "@/stores/counter"
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router';
const Store = useCounterStore()
const router = useRouter()
//逻辑
const logic = reactive({
  dialogFormVisible: false,
  isNo: false,
  istext: ''
})
//添加
const sourceadd = reactive({
  sourceInfoId: null,
  accountId: Store.accountcounter.accountId,
  productNameId: null,
  sourceproduction: "",
  sourceexpirationTime: null,
  sourcelicence: '',
  sourceCreamFirm: '',
  SourCecoverPicture: '',
  sourceCreamPerson: Store.accountcounter.accountNickName,
  AccountNickname: ''
})
//分页
const pagelist = reactive({
  pageIdex: 1,
  pageSize: 10,
  recordCount: 0
})
watch(pagelist, () => {
  getSource();
})
//显示
const source = ref([])
const getSource = () => {
  axios.get('http://localhost:5114/api/Managerment/GetSourceInfo', {
    params: {
      pageIndex: pagelist.pageIdex,
      pageSize: pagelist.pageSize
    }
  }).then(res => {
    source.value = res.data.data.data
    pagelist.recordCount = res.data.data.recordCount
  })
}
//商品名称
const getproduct: any = ref([])
const productList = () => {
  axios.get('http://localhost:5114/api/Managerment/Getproduct').then(res => {
    getproduct.value = res.data.data
  })
}
//图片
const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  sourceadd.SourCecoverPicture = response.imgbase;
  console.log(uploadFile)
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

//对话框的显示和修改
const add = (row: any) => {
  if (row == null) {
    sourceadd.productNameId = null
    sourceadd.sourceproduction = ''
    sourceadd.sourceexpirationTime = null
    sourceadd.sourcelicence = ""
    sourceadd.sourceCreamFirm = ""
    sourceadd.SourCecoverPicture = ""
    imageUrl.value = ""
    logic.isNo = false
    logic.istext = "添加"
  }
  else {
    sourceadd.sourceInfoId = row.sourceInfoId
    sourceadd.productNameId = row.productNameId
    sourceadd.sourceproduction = row.sourceproduction
    sourceadd.sourceexpirationTime = row.sourceexpirationTime
    sourceadd.sourcelicence = row.sourcelicence
    sourceadd.sourceCreamFirm = row.sourceCreamFirm
    imageUrl.value = row.sourCecoverPicture
    console.log(row.sourCecoverPicture)
    sourceadd.SourCecoverPicture = imageUrl.value
    sourceadd.sourceCreamPerson = row.sourceCreamPerson,
      logic.isNo = true
    logic.istext = "修改"
  }
  logic.dialogFormVisible = true
}

const addSource = () => {
  if (logic.isNo == false) {
    //添加
    axios.post('http://localhost:5175/api/Managerment/CreamSource', sourceadd).then(res => {
      if (res.data.code == 100) {
        ElMessage({
          message: '登陆成功',
          type: 'success',
        });
        getSource();
        logic.dialogFormVisible = false
      } else {
        ElMessage({
          message: res.data.message,
          type: 'error',
        });
      }
    })
  }
  else {
    //修改
    sourceadd.AccountNickname = Store.accountcounter.accountNickName
    axios.post('http://localhost:5175/api/Managerment/SourceInfoUpdate', sourceadd).then(res => {
      if (res.data.code == 500) {
        alert("修改成功");
        getSource();
        logic.dialogFormVisible = false
      }
    })
  }
}


//删除
const del = (sourceInfoId: any) => {
  ElMessageBox.confirm(
    '确定删除吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {

      let command = <any>{}
      command.sourceInfoId = sourceInfoId
      axios.post('http://localhost:5175/api/Managerment/SourceInfoDelete', command).then(res => {
        if (res.data.code == 400) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getSource();
        }
      })


    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}
//详细
const particulars = (row: any) => {
  router.push({
    path: '/Sourceinfo/particularsView',
    query: {
      sourceInfoId: row.sourceInfoId
    }
  })
}
//钩子函数
onMounted(() => {
  getSource();
  productList();
})
</script>


<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.el-button {
  width: 100px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>